#include "temp_password.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

/// 用来计算临时密码的hash code
/// 将字符串s转换成i32数值类型
/// 密码格式：AtguiguSmartLock001+8位时间戳

int32_t hash_code (char *s)
{
    int32_t hash = 0;
    int i = 0;
    while (i<19 +8) {
       hash = (hash << 5) - hash + ((uint8_t)s[i]|0);
       i++;
    }
    return hash;
}

uint8_t PASSWORD_ValidateTempPassword()
{
    time_t now;
    time(&now);
    uint64_t now_in_minutes = now / 60;
    now_in_minutes = now_in_minutes + 10;

    char buff[21];
    char* serial_number = "AtguiguSmartLock001";
    char key[27] = {0};


	// copy to buffer
	sprintf(buff, "%" PRIu64, now_in_minutes);
	// printf("buff: %s\r\n", buff);

	
	for(int i = 0; i < 19; i++)
	{
		key[i] = serial_number[i];
	}

	for(int j = 19; j < 27; j++)
	{
		key[j] = buff[j-19];
	}
	int32_t hash = hash_code(key);
	// 生成6位数字密码(000000-999999)
	int32_t temp_password = abs(hash % 1000000);
	
	// 调试打印
	printf("calculated temp_password: %06" PRId32 "\r\n", temp_password);

    return 0;
}

int main(){
	PASSWORD_ValidateTempPassword();
}